import { action } from 'mobx'
import * as api from 'lib/constants/api'
import { post } from 'lib/net'
import Toast from 'components/toast'
import Load from 'components/load'

export default class WXMiddleVM {
  constructor (props) {
    this.props = props
    this.PageInitialization()
  }

  @action PageInitialization = async () => {
    Load.loading(1, '加载中')
    let url = document.location.toString()
    let arrObj = url.split('?')
    if (arrObj.length > 1) {
      let arrPara = arrObj[1].split('&')
      var arr
      for (let i = 0; i < arrPara.length; i++) {
        arr = arrPara[i].split('=')
        if (arr != null && arr[0] === 'code') {
          this.params = {
            Code: arr[1],
            OpenId: window.sessionStorage.getItem('OpenId'),
            WZId: window.localStorage.getItem('UserId')
          }
          let response = await post(api.WZBINDUSER, this.params)
          if (response.Success) {
            Load.loading(2, '加载完成')
            window.sessionStorage.setItem('viewBox', 'true')
            this.props.history.go(-6)
          } else {
            Toast.fail(response.Message)
          }
        }
      }
    } else {
      window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxa5850dde18364498&redirect_uri=https://wzweb.shundaonetwork.com/wxMiddle&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'
    }
  }
}
